﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MyCanvasScaler : MonoBehaviour
{
    private List<CanvasRenderer> lst = new List<CanvasRenderer>();
    public float reX;
    public float reY;
    public int fontNewSize;
    private float xScale;
    private float yScale;
    private Vector3 vScale;
    private int sw;
    private int sh;

    public static MyCanvasScaler instance;

    private void Awake()
    {
        instance = this;
    }

    private void Start()
    {
        SetScale();
    }

    private void LateUpdate()
    {
        if (sw != Screen.width || sh != Screen.height)
        {
            SetScale();
        }
    }

    private void SetScale()
    {
        sw = Screen.width;
        sh = Screen.height;
        xScale = sw / reX;
        yScale = sh / reY;
        vScale.x = xScale;
        vScale.y = yScale;
        vScale.z = 1;
        lst.ForEach(item => item.transform.localScale = vScale);
    }

    public void AddPanel(CanvasRenderer cr)
    {
        lst.Add(cr);
        SetScale();
        FixeText(cr.transform);
    }

    private void FixeText(Transform tr)
    {
        Text txt = tr.GetComponent<Text>();
        if (txt != null)
        {
            float scale = (float) fontNewSize / txt.fontSize;

            txt.fontSize = fontNewSize;
            txt.rectTransform.sizeDelta = txt.rectTransform.sizeDelta * scale;
            txt.transform.localScale /= scale;
        }

        foreach (Transform t in tr)
        {
            FixeText(t);
        }
    }
}